<?php
/*
Copyedright by TNP
*/

require_once(__DIR__."/MySqlcon.php");
require_once(__DIR__."/MyRelation.php");

abstract class MyObject {
	protected static $database;
	protected static $data;
	protected static $tablename;
	protected static $pkname;
	protected $id;
	protected static $db;
	protected static $memkey;
	protected static $dataFields;
	protected static $relations;
	
	public function __construct($id=0, $data=0) {
		self::init();
		$this->id = $id;
		if ($this->id != 0) {
			$this->getById();
		}
		if (is_array($data)) {
			self::$data = $data;
			$this->dataToVars();
			if (isset($data[self::$pkname])) {
				$this->id = $data[self::$pkname];
			}
		}
	}
	
	public function getById() {
		$this->fromMemcached();
		if (!self::$data) {
			$sql = "SELECT * 
					FROM self::$tablename 
					WHERE self::$pkname='$this->id'
					LIMIT 1";
			$result = mysql_query($sql, self::$db);
			self::$data = mysql_fetch_array($result, MYSQL_ASSOC);
			$this->dataToVars();
			$this->toMemcached();
		}
	}
	
	public function save() {		
		$this->varsToData();		
		$sql = "INSERT INTO `".self::$tablename."` (";
		$sql .= implode (",", array_keys(self::$data));
		$sql .= ") VALUES ('";
		$sql .= implode ("','", self::$data);
		$sql .= "') ON DUPLICATE KEY UPDATE ";
		foreach (self::$data AS $key => $val) {
			if (isset($st)) $sql .= ","; else $st = true;
			$sql .= (''.$key.'="'.$val.'"');
		}
		$result = mysql_query($sql, self::$db);
		$this->toMemcached();
	}
	
	public static function getDataFields() {
		// todo: memcached!	
		if (is_array(self::$dataFields))
			return;	
		$sql = "describe `".self::$tablename."`";
		$result = mysql_query($sql, self::$db);
		$fields = array();
		while ($data = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$fields[] = $data['Field'];
		}
		self::$dataFields = $fields;
	}
	
	protected function dataToVars() {
		foreach (self::$data AS $key => $val) {
			$this->$key = $val;
		}
	}
	
	protected function varsToData() {
		foreach (self::$dataFields AS $field) {
			self::$data[$field] = isset($this->$field) ? $this->$field : "";
		}
	}
	
	protected function fromMemcached() {
		self::$data = MyMemory::get(self::$memkey.$this->id);
		$this->dataToVars();
	}
	
	protected function toMemcached() {
		MyMemory::set(self::$memkey.$this->id, self::$data);
	}
	
	protected static function init() {
		if (!self::$database) self::getStatic("database");
		if (!self::$tablename) self::getStatic("tablename");
		if (!self::$pkname) self::getStatic("pkname");
		if (!self::$db) self::$db = MySqlcon::getCon(self::$database);
		if (!self::$dataFields) self::getDataFields();
		if (!is_array(self::$relations)) self::getStatic("relations");
	}
	
	protected static function getStatic($name) {
		$class = get_called_class();
		self::$$name = $class::$$name;
	}
	
	protected function getRelations() {
		foreach (self::$relations AS $relation) {
			$relname = $relation['name'];
			$relobject = $relation['object'];
			$this->$relname = isset($this->$relname) ? $this->$relname : $relobject::getRelatedFrom($this);
		}
	}
	
	public static function findBy($key, $find, $getastable=false) {
		self::init();
		$sql = "SELECT * 
				FROM `".self::$tablename."`
				WHERE `$key` LIKE '$find'";
		$result = mysql_query($sql, self::$db);
		echo ("Query:".$sql."\n");
		echo mysql_error();
		$objects = array();
		while ($data = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$pkname = self::$pkname;
			$tempkey = $data[$pkname];
			$class = get_called_class();
			$objects[$tempkey] = new $class($pkname, $data);
		}
		
		if ($getastable) {
			$html = "<table border='1'>\n";
			$html .= self::getTableHeader();
			foreach ($objects AS $object) {
				$html .= $object->getTableLine();
			}
			$html .= "</table>\n";
			return $html;
		} else {
			return $objects;
		}
	}
	
	public static function findById($find, $getastable=false) {
		$objects = self::findBy(self::$pkname, $find, $getastable;
		return $objects[0];
	}
	
	public function getTableLine() {
		self::init();
		$html = "<tr>\n";
		foreach(self::$dataFields AS $field) {
			$html .= "\t<td>" . $this->$field . "</td>\n";
		}
		$html .= "</tr>\n";
		return $html;
	}
	
	public static function getTableHeader() {
		self::init();
		$html = "<tr>\n";
		foreach (self::$dataFields AS $field) {
			$html .= "\t<th>$field</th>\n";
		}
		$html .= "</tr>\n";
		return $html;
	}
	
	public static function getAddForm() {
		self::init();
		echo ("<form method='post'>\n");
		echo ("<table>\n");
		foreach (self::$dataFields AS $field) {
			echo ("<tr>\n");
			echo ("\t<td>$field:</td>\n");
			echo ("\t<td><input type='text' name='$field'></td>\n");
			echo ("</tr>\n");
		}
		echo ("<tr>\n");
		echo ("\t<td> </td>\n");
		echo ("\t<td><input type='submit' value='Add'></td>\n");
		echo ("</tr>\n");
		echo ("</table>\n");
		echo ("</form>\n");
	}
	
	public static function fromPostData() {
		$class = get_called_class();
		return new $class(0, $_POST);
	}
}

?>
